<?php

declare(strict_types=1);

namespace app\admin\controller;

use addons\Builder\facade\Builder;
use app\common\tool\Result;
use think\Response;
use think\response\Json;
use app\common\model\User;
use app\common\model\Logs;
//该文件为自动生成，请按需修改
class UserRole extends Base
{
    //主键，默认为id
    protected string $pk = 'id';

    //主模型
    protected string $model = '\app\common\model\UserRole';

    protected $append = ['type_text'];
    public function index(): string
    {
        return Builder::Table()
            ->autoStructure($this->model, $this->pk, 'barDemo,200')
            ->addRightButtons(['edit' => ['size' => '60%'], 'delete'])
            ->addTopButtons(['add' => ['size' => '60%']]) ->addSearch([
                ['title', '身份标题', 'input,Like'],
            ])
            ->addSearchList([
                [
                    'filed' => 'type',
                    'title' => '身份类型',
                    'child' => $this->model::getTypeList()
                ],
            ])
            ->fetch();
    }
    public static function getType(): array
    {
        return \app\common\model\UserRole::getType();
    }
    public function delete(): Response
    {
        try {
            $info = $this->model::where('id', $this->request->post($this->pk))->find();
            if (empty($info)) {
                return Result::fail('身份不存在');
            }
            $count = User::where('role_id', $info->id)->count();
            if ($count) {
                return Result::fail('该身份用户已占用！无法删除');
            }
            $this->model::destroy(['id' => $info->id]);
            Logs::adds('删除用户身份【' . $info->title . '】', $this->admin->id, $this->admin->admin_name);
            return Result::success('已删除');
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }

    }
}
